<template>
	<!-- 科奇版本 -->
	<view>
		<!-- 头部搜索框 -->
		<search :placeholder="$t('homepage.WarehouseManage.applyCode')" />
		<!-- 表格数据 -->
		<zy-table :headList="headList" :dataList="dataList" @editInput="editInput" :operationList="operationList"
			border>
		</zy-table>
		<!-- 底部按钮 -->
		<bottomBtn fixed :leftText="$t('public.reset')" :rightText="$t('public.materialCode')" @rightBtn="selectBtn"
			@leftBtn="resetBtn" :leftDisabled="dataList.length>0?false:true"
			:rightDisabled="dataList.length>0?false:true">
		</bottomBtn>
		<!-- 选择按钮弹窗 -->
		<zy-popup ref="zyPopup" type='dialog' :title="$t('public.materialCode')" @confirm="submit"
			:closeOnClickOverlay="false">
			<zy-forms :model="model" :rules="rules" labelWidth="100">
				<zy-form-item :label="$t('public.materialCode')" required>
					<zy-input v-model="model.materialNo"
						:placeholder="$t('public.pleaseInput')+$t('public.materialCode')" sufSlot
						@confirm="materialNoConfirm">
						<i class="iconfont icon-saoyisao" @click="rightIconMaterialNoHandler"></i>
					</zy-input>
				</zy-form-item>
				<zy-form-item :label="$t('public.productionNo')" required>
					<zy-input v-model="model.productNo"
						:placeholder="$t('public.pleaseInput')+$t('public.productionNo')" :disabled="inputDisabled"
						sufSlot>
						<i class="iconfont icon-saoyisao" @click="rightIconProductNoHandler"></i>
					</zy-input>
				</zy-form-item>
			</zy-forms>
		</zy-popup>
		<!-- 出库提交二次确认 -->
		<zy-popup ref="popup" :title="$t('homepage.WarehouseManage.outstorageSure')" type="dialog" @confirm="submitBtn">
			{{$t('homepage.WarehouseManage.isSure')}}{{model.type}}{{$t('public.question')}}
		</zy-popup>
	</view>
</template>
<script>
	import {
		getStorehouseApplyById,
		queryDictByType,
		queryTreeList,
		saveStorehouseOut
	} from "@/api/homepage.js"
	import search from "@/components/topSearch/index.vue";
	import bottomBtn from "@/components/bottomBtn/index.vue";
	export default {
		components: {
			search,
			bottomBtn
		},
		data() {
			return {
				//表格表头
				headList: [{
					name: this.$t('homepage.WarehouseManage.instorageCode'),
					key: 'barcode',
					width: 150
				}, {
					name: this.$t('public.surplusNum'),
					key: 'surplusNum',
					sum: true
				}, {
					name: this.$t('public.deliveryNum'),
					key: 'num',
					edit: true,
					type: 'number',
					sum: true
				}, {
					name: this.$t('homepage.WarehouseManage.applyNum'),
					key: 'applyNum',
				}, ],
				dataList: [], //表格数据
				//表格操作列
				operationList: [{
					kind: "button",
					type: "warn",
					handle: this.delBtn,
					label: this.$t('public.del'),
				}],
				//弹窗表单数据
				model: {
					materialNo: '',
					productNo: ''
				},
				//form校验
				rules: {
					materialNo: {
						required: true,
						message: this.$t('public.pleaseInput'),
						trigger: ['blur', 'change']
					},
					productNo: {
						required: true,
						message: this.$t('public.pleaseInput'),
						trigger: ['blur', 'change']
					},
				},
				inputDisabled: true,
				id: '',
				materialCode: '',
			}
		},
		onLoad() {
			this.getscancodedate()
		},
		onUnload() {
			// 移除监听事件      
			uni.$off('scancodedate')
			uni.$off('scancodepopdate')
		},
		methods: {
			//主页获取箱号扫描事件
			getscancodedate() {
				// 移除监听“添加扫描”弹窗事件
				uni.$off('scancodepopdate')
				//PDA扫描主页指示单号
				var _this = this
				uni.$on('scancodedate', function(data) {
					_this.searchList(data.code.replace(/\s/g, ""))
				})
			},
			//“弹窗物料编码”获取扫描事件
			getscancodepopdate() {
				// 移除监听“指示单号”事件
				uni.$off('scancodedate')
				//PDA扫描“添加扫描”弹窗事件
				var _this = this
				uni.$on('scancodepopdate', function(data) {
					_this.model.materialNo = data.code.replace(/\s/g, "")
					_this.materialNoConfirm()
				})
			},
			searchList(e) {
				getStorehouseApplyById({
					id: e,
				}).then((res) => {
					if (res.code == 0) {
						console.log(res.data)
						this.dataList = res.data
						this.dataList.forEach((item, index) => {
							// 出库数量默认为0
							this.dataList[index].num = 0
							this.dataList[index].applyNum = item.applyNum - item.outNum
						})
						this.materialCode = res.data[0].materialCode
						this.id = e
					} else {
						uni.showToast({
							title: res.message,
							icon: "none",
							duration: 3000
						})
					}
					this.disabled = false
				}).catch((res) => {
					uni.showToast({
						title: res.message,
						icon: "none",
						duration: 3000
					})
				});
			},
			//编辑出库数量
			editInput(val) {
				let applyNum = Number(this.dataList[0].applyNum)
				let num = ""
				let sum = "";
				let surplusSum = ""
				sum = this.dataList.reduce((prev, curr) => {
					const value = parseInt(curr.num)
					if (value) {
						return parseInt(prev) + parseInt(curr.num);
					} else {
						return parseInt(prev);
					}
				}, 0);
				if (sum > applyNum) {
					uni.showToast({
						title: this.$t('homepage.WarehouseManage.smallerApplyNum') + this.$t('public.colon') +
							applyNum,
						icon: "none",
						duration: 3000
					})
					surplusSum = Number(this.dataList[val.index].surplusNum) - Number(sum)
					this.dataList[val.index].num = 0
				} else {
					if (Number(this.dataList[val.index].surplusNum) < Number(val.item.num)) {
						num = Number(this.dataList[val.index].surplusNum)
						uni.showToast({
							title: this.$t('public.max') + this.$t('public.colon') + num,
							icon: "none",
							duration: 3000
						})
						this.dataList[val.index].num = num
					} else {
						num = Number(this.dataList[val.index].applyNum)
					}
				}
			},
			// 删除数据事件
			delBtn(item, index) {
				this.dataList.splice(index, 1);
			},
			//重置按钮
			resetBtn() {
				uni.redirectTo({
					url: "/pages/HomePage/WarehouseManage/StorageManagement/Outstorage/index"
				})
			},
			// 底部选择按钮事件
			selectBtn() {
				this.$refs.zyPopup.open()
				this.getscancodepopdate()
			},
			// 物料编码弹窗扫描
			rightIconMaterialNoHandler() {
				var mpaasScanModule = uni.requireNativePlugin("Mpaas-Scan-Module")
				mpaasScanModule.mpaasScan({
						// 扫码识别类型，参数可多选，qrCode、barCode，不设置，默认识别所有
						'scanType': ['qrCode', 'barCode'],
						// 是否隐藏相册，默认false不隐藏
						'hideAlbum': false
					},
					(ret) => {
						if (ret.resp_result) {
							this.model.materialNo = ret.resp_result.replace(/\s/g, "");
							this.materialNoConfirm()
						}
					})
			},
			rightIconProductNoHandler() {
				var mpaasScanModule = uni.requireNativePlugin("Mpaas-Scan-Module")
				mpaasScanModule.mpaasScan({
						// 扫码识别类型，参数可多选，qrCode、barCode，不设置，默认识别所有
						'scanType': ['qrCode', 'barCode'],
						// 是否隐藏相册，默认false不隐藏
						'hideAlbum': false
					},
					(ret) => {
						if (ret.resp_result) {
							this.model.productNo = ret.resp_result.replace(/\s/g, "");
						}
					})
			},
			// "物料编码"弹窗事件
			materialNoConfirm() {
				if (this.model.materialNo !== this.materialCode) {
					uni.showToast({
						title: this.$t('homepage.WarehouseManage.mismatch'),
						icon: "none",
						duration: 3000
					})
					this.model.materialNo = ''
				} else {
					this.inputDisabled = false
				}
			},
			//出库二次确认按钮事件
			submit() {
				if (!this.model.materialNo || !this.model.productNo) {
					uni.showToast({
						title: this.$t('public.pleaseInput') + "！",
						icon: "none",
						duration: 3000
					})
				} else {
					this.$refs.popup.open()
				}
			},
			//确认出库
			submitBtn() {
				console.log(this.model.productNo, this.dataList)
				saveStorehouseOut({
					id: this.id,
					productionNo: this.model.productNo,
					dataArray: JSON.stringify(this.dataList), //库存数组 （扫码获取的数据，多个逗号隔开）
				}).then((res) => {
					if (res.code == 0) {
						uni.showToast({
							title: res.message,
							icon: "none",
							duration: 3000
						})
						this.resetBtn()
					} else {
						uni.showToast({
							title: res.message,
							icon: "none",
							duration: 3000
						})
					}
				}).catch((res) => {
					uni.showToast({
						title: res.message,
						icon: "none",
						duration: 3000
					})
				});
			},
		}
	}
</script>
<style lang="scss" scoped>
	.formItem {
		width: calc(100% - 40rpx);
		padding: 20rpx;
		display: flex;
		border: 1px solid #e9e9e9;
		border-radius: 10rpx;
		background-color: #f5f5f5;
	}

	.formInput {
		margin: auto 0;
		width: 100%;
		border: none;
		outline: none;
		font-size: 32rpx;
		z-index: 999999;
	}

	.iconfont {
		margin: auto 0 auto 10rpx;
		font-size: 28rpx;
		color: #999999;
	}
</style>